// 1. 导入 http 模块
const http = require('http')
const path = require('path')
const db=require('../db模块/db模块.js')
const dayjs=require('dayjs')
// 2. 创建 web 服务器实例
const server = http.createServer()

// 3. 启动服务器
server.listen(8848, () => {
//   console.log('服务器启动了', 'http://127.0.0.1:8848');
  console.log('my server start work')
})

// 4. 为服务器实例绑定 request 事件，监听客户端的请求
server.on('request', (request, response) => {
    // let url = request.url
    // let method=request.method
    // 解构
    let { url, method } = request
    let data = {}
    if (method.toLowerCase()==='get') {
        if (url==='/api/news') {
            data = db.news()
            data.forEach(t => {
                t.publish_time=dayjs(t.publish_time).format('YYYY-MM-DD HH:mm:ss')
            });
        }
      else  if (url==='/api/students') {
            data=db.students()
        }
       else if (url==='/api/lucystar') {
            data=db.lucystar()
        }
    }
  // 设置响应的内容为JSON
 response.setHeader('Content-Type', 'application/json; charset=utf-8')
  // 不能直接响应 对象/数组 需要转为字符串
  response.setHeader('Access-Control-Allow-Origin','*')
    response.end(JSON.stringify(data))
})